package com.navi.core.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by admin on 2017/7/20.
 */

@Component
public class ExecutorUtil {

//    private ExecutorUtil() {
//
//    }

//    @Value("${executor.threadcnt}")
//    private Integer threadCnt;

    private ExecutorService executorService;
    @PostConstruct
    public void init(){
        executorService = Executors.newCachedThreadPool();
//        executorService = Executors.newWorkStealingPool(threadCnt);
//        executorService = Executors.newFixedThreadPool(50);
    }


    @PreDestroy
    public void shutdown(){
        tearDown(executorService);
    }

    public ExecutorService getExecutorService() {
        return executorService;
    }

    public static ExecutorService getExecutorService(int threadCnt) {
        return Executors.newFixedThreadPool(threadCnt);
    }

    public static void tearDown(ExecutorService executorService) {
        try {
            executorService.shutdown();
            executorService.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.out.println("tasks interrupted");
        } finally {
            if (!executorService.isTerminated()) {
                System.out.println("cancel non-finished tasks");
            }
            executorService.shutdownNow();
            System.out.println("shutdown finished");
        }
    }


    public static void main(String[] args) {
        final int i = Runtime.getRuntime().availableProcessors();
        System.out.println("核心数" + i);
//        System.getProperties().forEach((k, v) -> {
//            System.out.println(k + " : " + v);
//        });
//        System.out.println(HistoryContext.getIp());
    }

}
